package token

import (
	"encoding/json"
	"time"
	"vblog/apps/user"
	"vblog/common"
)

func NewToken() *Token {
	return &Token{
		CreatedAtRequest:   common.NewCreatedAtRequest(),
		UpdateAtRequest:    common.NewUpdateAtRequest(),
		CreateTokenRequest: NewCreateTokenRequest(),
	}
}

func NewCreateTokenRequest() *CreateTokenRequest {
	return &CreateTokenRequest{
		AccessTokenExpiredAt:  time.Now().Unix() + AccessTokenExpired,
		RefreshTokenExpiredAt: time.Now().Unix() + RefreshTokenExpired,
	}
}

type Token struct {
	*common.CreatedAtRequest
	*common.UpdateAtRequest
	*CreateTokenRequest
}

// https://typonotes.com/posts/2020/12/11/tips-auto-add-tags/
type CreateTokenRequest struct {
	UserId                int64     `json:"user_id,omitempty"`
	Username              string    `json:"username,omitempty"`
	AccessToken           string    `json:"access_token,omitempty"`
	AccessTokenExpiredAt  int64     `json:"access_token_expired_at,omitempty"`
	RefreshToken          string    `json:"refresh_token,omitempty"`
	RefreshTokenExpiredAt int64     `json:"refresh_token_expired_at,omitempty"`
	Role                  user.Role `json:"role" gorm:"-"`
}

func (t *Token) GenAccessToken() error {
	accessToken, err := common.GenToken()
	if err != nil {
		return err
	}
	t.AccessToken = accessToken
	t.AccessTokenExpiredAt += AccessTokenExpired
	t.UpdatedAt = time.Now().Unix()
	return nil
}

func (t *Token) GenRefreshToken() error {
	refreshToken, err := common.GenToken()
	if err != nil {
		return err
	}
	t.RefreshToken = refreshToken
	return nil
}

func (t *Token) TableName() string {
	return AppName
}

func (t *Token) String() string {
	b, err := json.MarshalIndent(t, " ", " ")
	if err != nil {
		return ""
	}
	return string(b)
}
